package chat.aylan.top.wind;
/**
 * 主程序
 */

import chat.aylan.top.commons.Constants;
import chat.aylan.top.commons.Group;
import chat.aylan.top.commons.Information;
import chat.aylan.top.commons.User;
import chat.aylan.top.communicate.ReceiverThread;
import chat.aylan.top.communicate.Sender;
import chat.aylan.top.database.service.UserServicce;
import com.alibaba.fastjson.JSONObject;

import javax.swing.*;
import javax.swing.border.MatteBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.Socket;
import java.sql.SQLException;
import java.util.List;

public class ManagerWind extends JFrame {

    private int width = 320;
    private int height = 580;
    MyPanel panel;

    public static List<User> friends;   // 所有的好友
    DefaultListModel listModel;         // 好友列表模型

    public static User user;            // 当前用户
    public static int onlines = 0;      // 在线人数

    public static Sender sender;        // 发送器

    /**
     *  链接服务器
     */
    public void connect() {
        try {
            Socket socket = new Socket(Constants.ChatHost,10001);
            ReceiverThread receiverThread = new ReceiverThread(socket,this);
            new Thread(receiverThread).start();
            sender = new Sender(socket);
            sender.send(new Information(1));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public ManagerWind() {
        this.setSize(width, height);
        panel = new MyPanel();
        panel.setLayout(new BorderLayout());
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((int) (screenSize.getWidth()) - width - 30, 60);
        setHeader();
        setFooter();
        this.add(panel);
        this.setVisible(true);

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                offline();  // 通知自己下线
                super.windowClosing(e);
            }
        });
    }


    // 在列表里修改好友状态
    public void updateFriends(User user,short status) {
        for (User item : ManagerWind.friends){
            int index  = ManagerWind.friends.indexOf(item);
            if(item.getId() == user.getId()){
                ManagerWind.friends.get(index).setStatus(status);
                if(status == 0){
                    onlines--;
                }
            }
            listModel.setElementAt(item.getUsername()+"--"+item.getState()+"--新消息 :"+item.getMsg(),index+1);
        }

        listModel.setElementAt("聊天室 --- "+onlines+" 个人在线,有 "+Group.getInstance().getMsg()+" 个新消息",friends.size()+1);
        this.revalidate();
    }

    /**
     * 管理聊天窗口
     * @param user
     * @param message
     */
    public void someOneSay(JSONObject user,String message){
        for (User friend : ManagerWind.friends){
            if(friend.getId() == user.getInteger("id")){
                if(friend.getWind() != null){
                    friend.getWind().updatePane("  "+friend.getUsername()+" :   ",message);
                }else{
                    friend.setWind(new ChatWind(480,320,friend.getId()));
                    friend.getWind().updatePane("  "+friend.getUsername()+" :   ",message);
                }
                if(!friend.getWind().isVisible()){
                    friend.setMsg(friend.getMsg()+1);
                }
                updateFriend(friend,ManagerWind.friends.indexOf(friend)+1);
            }
        }
    }

    //  更新 好友状态
    private void updateFriend(User friend,int index){
        listModel.setElementAt(friend.getUsername()+"--"+friend.getState()+"--新消息 :"+friend.getMsg(),index);
        this.revalidate();
    }

    /// 更新群状态
    public void updateGroup(JSONObject object){
        Group.getInstance().wind.updatePane(object.getJSONObject("user").getString("username"),object.getString("message"));
        if(!Group.getInstance().wind.isVisible()){
            Group.getInstance().setMsg(Group.getInstance().getMsg()+1);
        }
        listModel.setElementAt("聊天室 --- "+onlines+" 个人在线,有 "+Group.getInstance().getMsg()+" 个新消息",friends.size()+1);
        this.revalidate();
    }

    private class MyPanel extends JPanel {
        @Override
        public void paint(Graphics graphics){
            super.paint(graphics);
        }
    }

    /**
     *  创建列表
     */
    public void setList(){

        JPanel listPanel = new JPanel();
        listPanel.setSize(width,height-40);
        listPanel.setBackground(Color.red);

        JList list = new JList();

        listModel = new DefaultListModel();
        listModel.addElement(user.getUsername()+"--"+user.getState());
        for(User friend:friends){
            listModel.addElement(friend.getUsername()+"--"+friend.getState()+"--新消息："+friend.getMsg());
        }
        listModel.addElement("聊天室 -- "+onlines+" 个人在线,有 "+Group.getInstance().getMsg()+" 个新消息");
        list.setPreferredSize(new Dimension(width-1,40));
        list.setModel(listModel);
        setChatEvent(list);
        panel.add(list,BorderLayout.CENTER);
        revalidate();
    }


    // 好友被点击事件设置和处理
    private void setChatEvent(JList list){
        list.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                int index = list.getSelectedIndex();
                int size = listModel.getSize();
                if(index > 0 && index < (size-1)){
                   if( friends.get(index - 1).getWind() == null){
                       ChatWind wind = new ChatWind(480,320,friends.get(index - 1).getId());
                       friends.get(index - 1).setWind(wind);
                       wind.setVisible(true);
                   }else{
                       friends.get(index - 1).getWind().setVisible(true);
                   }
                   friends.get(index-1).setMsg(0);
                   updateFriend(friends.get(index - 1),index);
                }else if(index == (friends.size()+1)){
                    ChatWind wind = Group.getInstance().wind;
                    wind.setVisible(true);
                    Group.getInstance().setMsg(0);
                    listModel.setElementAt("聊天室 --- "+onlines+" 个人在线,有 "+Group.getInstance().getMsg()+" 个新消息",friends.size()+1);
                    ManagerWind.this.revalidate();
                }
            }
        });
    }

    private void setHeader(){
        JPanel header = new JPanel(new FlowLayout());
        header.setBorder(new MatteBorder(0,0,1,0,new Color(569009)));
        JLabel name = new JLabel("hello , "+user.getUsername()+"!");
        name.setBorder(BorderFactory.createEmptyBorder(10,0,10,0));
        header.add(name);
        panel.add(header);
        JPanel head = header;
        head.setLocation(0,50);
        panel.add(head,BorderLayout.NORTH);
    }

    private void setFooter(){
        JPanel foot = new JPanel(new FlowLayout());
        foot.add(new JLabel("oylan 软件开发工作室"));
        panel.add(foot,BorderLayout.SOUTH);
    }

    //* 下线 *//
    private void offline(){
        UserServicce service = new UserServicce();
        user.setStatus((short) 0);
        try {
            service.updateUser(user);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
